<!--
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
-->
<!--
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
-->
<template>
  <div>
    <el-button type="primary" size="default" @click="handleAddEdit(null)">
      新增角色
    </el-button>

    <el-table :data="roleList" border stripe>
      <el-table-column prop="name" label="角色名称" width="150" />
      <el-table-column prop="checkedKeys" label="角色权限">
        <template #default="scope">
          <el-tag type="primary" v-for="item in scope.row.checkedKeys">
            {{ routeMap[item] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleAddEdit(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确定不是手抖了？"
            confirmButtonText="确认"
            cancelButtonText="取消"
            @confirm="handleDel(scope.row, scope.$index)"
          >
            <template #reference>
              <el-button type="danger" size="small" @click="">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer title="角色管理" v-model="drawer" direction="rtl" size="30%">
      <RoleForm
        :row-data="editData"
        v-if="drawer"
        @update-role="handleRoleList"
      />
    </el-drawer>
  </div>
</template>

<script>
import { roleGet, roleDel } from "@/api/user-api";
import RoleForm from "./components/role-form.vue";
import { routeMap } from "@/utils/tools";
export default {
  components: {
    RoleForm,
  },
  data() {
    return {
      editData: null, //区分新增与编辑
      roleList: [],
      drawer: false,
      routeMap,
    };
  },
  created() {
    roleGet().then((res) => {
      this.roleList = res.data.results;
    });
    console.log("路径-名称", routeMap);
  },
  methods: {
    // 新增、编辑的按钮事件函数
    handleAddEdit(row) {
      this.drawer = true;
      this.editData = row;
    },
    //更新本地列表
    handleRoleList({ newObj, type }) {
      console.log("父级接收到了数据", newObj);
      this.drawer = false;
      if (type == 2) {
        this.roleList.push(newObj); //新增
        return;
      }
      //更新列表
      for (let i = 0; i < this.roleList.length; i++) {
        if (this.roleList[i].objectId == objectId) {
          this.roleList[i] = newObj;
          return;
        }
      }
    },
    //删除
    handleDel({ objectId }, idx) {
      console.log(objectId, idx);
      roleDel(objectId).then((res) => {
        this.roleList.splice(idx, 1);
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
